package com.al.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DBHelper {
	//属性
		private static final String URL = "jdbc:mysql://localhost:3306/jdbcdemo?serverTimezone=UTC";
		private static final String USER = "root";
		private static final String PASSWORD = "";
		Connection conn = null;
		PreparedStatement pstat = null;
		ResultSet rs = null;
		
		//建立连接
		private void getConnection() throws ClassNotFoundException, SQLException {
			//加载驱动
			Class.forName("com.mysql.cj.jdbc.Driver");
			conn = DriverManager.getConnection(URL, USER, PASSWORD);
		}
		//给增删改一个方法
		public int executeUpdate(String sql, Object...objects) throws SQLException, ClassNotFoundException {
			getConnection();
			//创建语句发送器
			pstat = conn.prepareStatement(sql);
			//给占位符赋值
			setObject(objects);
			return pstat.executeUpdate();
		}
		private void setObject(Object...objects) throws SQLException {
			for(int i = 0; i < objects.length; i++) {
				pstat.setObject(i+1, objects[i]);
			}
		}
		//查的方法
		public ResultSet executeQuery(String sql, Object...objects) throws ClassNotFoundException, SQLException {
			getConnection();
			//创建语句发送器
			pstat = conn.prepareStatement(sql);
			//给占位符赋值
			setObject(objects);
			return pstat.executeQuery();
		}
		public void close() throws SQLException {
			if(rs != null) {
				rs.close();
			}
			if(pstat != null) {
				pstat.close();
			}
			if(conn != null) {
				conn.close();
			}
		}
}
